//引入包资源
const gulp=require('gulp')
const uglify=require('gulp-uglify')
const babel=require('gulp-babel')
const cleanCSS =require('gulp-clean-css')
const sass=require('gulp-sass')(require('sass'))
const htmlmin=require('gulp-htmlmin')
const del=require('del')
const connect=require('gulp-connect')
const jsonmin=require('gulp-jsonminify')

//定义变量，保存各种资源路径
const paths={
    js:{
        src:'public/js/**/*.js',//js源文件路径
        dest:'dist/js'//js处理后的文件路径
    },
    css:{
        src:'public/css/**/*.css',
        dest:'dist/css'
    },
    scss:{
        src:'public/scss/**/*.scss',
        dest:'dist/css'
    },
    html:{
        src:'public/**/*.html',
        dest:'dist'
    },
    libs:{
        src:'public/libs/**/*.*',
        dest:'dist/libs'
    },
    imgs:{
        src:'public/img/**/*.*',
        dest:'dist/img'
    },
    json:{
        src:'public/json/**/*.json',
        dest:'dist/json'
    }
}

//定义任务函数
//处理js资源
function scripts(){
    return gulp.src(paths.js.src)
        .pipe(babel({
            presets:['env']
        }))
        .pipe(uglify())
        .pipe(gulp.dest(paths.js.dest))
        .pipe(connect.reload())
}
//处理css资源
function styles(){
    return gulp.src(paths.css.src)
        .pipe(cleanCSS())
        .pipe(gulp.dest(paths.css.dest))
        .pipe(connect.reload())
}
//编译scss文件
function buildScss(){
    return gulp.src(paths.scss.src)
        .pipe(sass({outputStyle:'compressed'}))
        .pipe(gulp.dest(paths.scss.dest))
        .pipe(connect.reload())
}
//处理html文件
function html(){
    return gulp.src(paths.html.src)
        .pipe(htmlmin({collapseWhitespace:true,minifyCSS:true,minifyJS:true}))
        .pipe(gulp.dest(paths.html.dest))
        .pipe(connect.reload())
}
function jsonMin(){
    return gulp.src(paths.json.src)
        .pipe(jsonmin())
        .pipe(gulp.dest(paths.json.dest))
        .pipe(connect.reload())
}
//定义监视任务
function watch(){
    gulp.watch(paths.scss.src,buildScss)
    gulp.watch(paths.js.src,scripts)
    gulp.watch(paths.css.src,styles)
    gulp.watch(paths.html.src,html)
    gulp.watch(paths.imgs.src,copyImgs)
    gulp.watch(paths.json.src,jsonMin)
}

//清理dist目录
function clean(){
    return del(['dist'])
}
//复制无需特数处理的资源
function copyLibs(){
    return gulp.src(paths.libs.src)
        .pipe(gulp.dest(paths.libs.dest))
}
//复制图片资源
function copyImgs(){
    return gulp.src(paths.imgs.src)
        .pipe(gulp.dest(paths.imgs.dest))
        .pipe(connect.reload())
}

//启动webserver
function server(){
    connect.server({
        root:'dist',
        port:8080,
        livereload:true
    })
}
//形成处理流程
const build=gulp.series(clean,gulp.parallel(styles,scripts,buildScss,html,jsonMin,copyLibs,copyImgs,watch,server))
//导出任务
exports.scripts=scripts
exports.styles=styles
exports.buildScss=buildScss
exports.watch=watch
exports.html=html
exports.clean=clean
exports.build=build
exports.copyLibs=copyLibs
exports.copyImgs=copyImgs
exports.server=server

//默认任务
exports.default=build